package allwe.nacos.config;

import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Properties;

//@Configuration
public class NacosConfig {

    @Value("${nacos.server-addr}")
    private String serverAddr;

    @Value("${spring.application.name}")
    private String serviceName;

    @Value("${server.port}")
    private String port;

    @Bean
    public NamingService namingService() throws NacosException {
        // nacos注册中心配置
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
        // 服务配置
        Instance instance = new Instance();
        instance.setIp(System.getenv("ip"));                // 服务的 IP 地址
        instance.setPort(Integer.parseInt(port));   // 服务的端口
        instance.setServiceName(serviceName);       // 服务名称
        // 创建 Nacos NamingService 实例
        NamingService namingService = NamingFactory.createNamingService(properties);
        // 注册服务到 Nacos
        namingService.registerInstance(serviceName, instance); // 注册服务实例
        return namingService;
    }
}
